<template class="wrap">
  <div id="element-library" class="library"  tabindex="1" @keyup.46="">
    <div class="element-library-toolbar">
      <!--&lt;!&ndash;   后退按钮   &ndash;&gt;-->
<!--      <ElementLibraryIconButton icon="el-icon-back"-->
<!--                                :title="$t('message.ElementLibrary.back')"-->
<!--                                :disable="!hasBack()"-->
<!--                                @click="back()"/>-->
<!--      &lt;!&ndash;   前进按钮   &ndash;&gt;-->
<!--      <ElementLibraryIconButton icon="el-icon-right"-->
<!--                                :title="$t('message.ElementLibrary.go')"-->
<!--                                :disable="!hasGo()"-->
<!--                                @click="go()"/>-->
      <!--   添加到库按钮   -->
<!--      <div class="element-library-icon-button element-library-hover model-icon text-icon-light bg-color1 text-color1 tw-flex tw-justify-center tw-items-center"-->
<!--           :title="$t('message.ElementLibrary.addToElementLibrary')"-->
<!--           @click="">-->
<!--        <img src="./images/新建模型库.svg" width="20" height="20" alt="" class="svg-icon">-->
<!--      </div>-->
      <ElementLibraryIconButton icon="el-icon-document-add"
                           :title="$t('message.ElementLibrary.addToElementLibrary')"
                           @click="addToElementLibrary"/>
      <!--   新建文件夹按钮   -->
<!--      <ElementLibraryIconButton icon="el-icon-folder-add"-->
<!--                                :title="$t('message.ElementLibrary.createFolder')"-->
<!--                                :disable="!hasAdd()"-->
<!--                                @click="openCreateFolderModal"/>-->
      <!--   搜索框按钮   -->
      <ElementLibraryIconButton icon="el-icon-search"
                                :active="openSearch"
                                :title="$t('message.ElementLibrary.search')"
                                @click="search"/>
      <!--   返回上一级按钮   -->
      <ElementLibraryIconButton icon="el-icon-top"
                           :title="$t('message.ElementLibrary.backTop')"
                           />
<!--      <img src="./images/Backward.svg" width="24" height="24" alt="">-->
<!--      &lt;!&ndash;&lt;!&ndash;   前进按钮   &ndash;&gt;&ndash;&gt;-->
<!--      <img src="./images/Forward.svg" width="24" height="24" alt="">-->
    </div>
    <!--  要素库检索  -->
    <div class="element-library-search">
      <ElementLibrarySearchInput v-show="openSearch"
                            v-model="searchContent"
                            :search-mode="searchMode"
                            :placeholder="$t('message.ElementLibrary.inputSearchContent')"
                            @search="searchEventHandler"
                            @click="searchItem"/>
    </div>
    <div>
      <!--  要素库-库列表  -->
      <ElementLibraryLib v-if="loadedLib" @hook:mounted="libMountedEventHandler" ref="lib" :selected-item="selectItem"/>
    </div>

    <div ref="resizeBar" class="drag-bar"></div>
    <div class="details-panel">{{ $t("message.ElementLibrary.detailsPanel") }}</div>
    <!--  知识库预览列表  -->
    <ElementLibraryFilePreview :open-folder="openFolder" :select-item="selectItem" :preview-list="previewList"/>
    <!--  右键菜单  -->
    <context-menu rightMenuId="elementLibraryRightMenu"
                  :mouseEvent="mouseEvent"
                  selectedRightMenuId="elementLibraryRightMenu">
      <template #menu>
        <context-menu-item v-for="menuItem in initMenu()" :item="menuItem" :key="menuItem.id"/>
      </template>
    </context-menu>
    <div id="modal-container">
      <component v-if="showModal('knowledgeSelectParametric')"
                 :key="'knowledgeSelectParametric'"
                 v-bind="modalParams('knowledgeSelectParametric')"
                 :is="'knowledge-select-parametric'">
      </component>
    </div>
  </div>
</template>
<script>
  import ElementLibraryIconButton from "./ElementLibraryIconButton.vue";
  import {elementLibraryCmd} from "../../../Command/ElementLibrary/ElementLibraryCommand";
  import DialogMixin from "../DialogMixin";
  import ElementLibrarySearchInput from "./ElementLibrarySearchInput.vue";
  import ElementLibraryLib from "./ElementLibraryLib.vue";
  import useDragResizeY from "./js/useDragResizeY";
  import {eventBus} from "../../../eventbus/eventbus";
  import ElementLibraryFilePreview from "./ElementLibraryFilePreview.vue";
  import {LibraryItem, LibraryResultItem, LibraryType} from "./js/ElementLibraryTypes";
  import {request} from "../../../util/Request";
  import elementLibraryManager from "./js/ElementLibraryManager";
  import {ContextItem} from "../../js/menu/ContextItem";
  import {elementLibraryItemMenu, elementLibraryItemPreviewMenu} from "./js/menu/ElementLibraryItemMenu";
  import ModalSelectParametricOption from "../../WorkAreaComponents/ElementLibrary/ModalSelectParametricOption.vue"
  import ModalContainerMixin from "../../BaseComponents/BaseModal/JS/ModalContainerMixin"
  export default {
    mixins: [DialogMixin,ModalContainerMixin],
    components: {
      ElementLibraryFilePreview,
      ElementLibrarySearchInput,
      // ElementLibraryFilePreview,
      ElementLibraryLib,
      ElementLibraryIconButton,
      ModalSelectParametricOption,
      "knowledge-select-parametric": () =>
        import("../../WorkAreaComponents/ElementLibrary/ModalSelectParametricOption.vue"),
    },
    data() {
      return {
        /**
         * @type {LibraryItem} 选中的Item，最后会作用域选中效果
         */
        selectItem: null,
        previewList: [],
        elementLibraryRightMenu: [],
        /**
         * @type {LibraryItem} 打开的文件夹项，最后会作用与预览视图
         */
        openFolder: null,
        mouseEvent: null,
        searchMode: false, // 检索模式是否开启
        openSearch: false, // 是否开启搜索框
        /**
         * @type {string} 检索框绑定的值
         */
        searchContent: "",
        searchResult: [],
        library: true, // 防止要素库以外使用知识库列表会展开选项
        loadedLib: false,
        afterHistoryRecord: [],
        beforeHistoryRecord: [],
      }
    },
    provide() {
      return {
        rightClickItem: this.rightClickItem,
        selectItemHandler: this.selectItemHandler,
        openFolderEventHandler: this.openFolderEventHandler,
        library: this.library,
        scrollElementLibraryContainer: this.scrollElementLibraryContainer,
      }
    },
    created() {
      this.initState();
      // 初始化菜单
      this.initMenu();
      this.initEvent();
      // knowledgeBaseManager.rightNavigationPanelIsActive = true;
    },
    beforeDestroy() {
      this.destroyEvent();
      this.loadedLib = false;
      // elementLibraryManager.clearTempSelectedItem();
      // knowledgeBaseManager.rightNavigationPanelIsActive = false;
    },
    methods: {
      changePluginContainerHeight() {
        elementLibraryCmd.changePluginContainerHeight({minWidth: this.$el.clientWidth, maxHeight: this.$el.clientHeight})
      },
      libMountedEventHandler() {
        useDragResizeY(this.$refs.lib.$el, this.$refs.resizeBar);
      },
      initState() {
        this.selectItem = null;
        this.openFolder = null;
        this.mouseEvent = null;
        this.searchResult = [];
        this.previewList = [];
        this.elementLibraryRightMenu = [];
        this.searchContent = "";
        // knowledgeBaseManager.clearHistoryRecord();
        this.searchMode = false;
        this.openSearch = false;
        this.loadedLib = true;
      },
      /**
       * 滚动容器到指定位置
       * @param itemElement {HTMLDivElement}
       */
      scrollElementLibraryContainer(itemElement) {
        if (!itemElement) return;
        const offsetTop = itemElement.offsetTop;
        // 滚动到该位置
        this.$refs.lib.scrollPosition(offsetTop);
      },
      hasAdd() {
        let bAdd = true;
        if (this.selectItem && this.selectItem.libraryType !== LibraryType.FOLDER) {
          bAdd = false;
        }
        return bAdd;
      },
      // 打开创建知识库文件夹
      openCreateFolderModal() {
        if (this.selectItem && this.selectItem.id !== '-1') {
          // 打开并展开文件夹
          this.openFolderEventHandler(this.selectItem);
          eventBus.emit("openElementLibraryFolder", this.selectItem.id);
        }
        // 在一帧后开始预创建文件夹
        this.$nextTick(() => {
          elementLibraryManager.preCreateFolder(this.selectItem);
        })
      },
      /**
       * 无历史记录的打开文件夹
       * 为什么会存在两个打开事件，原因在于历史记录在操作的时候不允许添加一个新的历史记录
       * @param folderId {string}
       */
      openFolderEventHandlerNoHistory(folderId) {
        // 在回退记录中为0的话，关闭所有文件夹展开
        if (folderId === "0") {
          eventBus.emit("unfoldElementLibraryFolder", [], false, "0");
        }
        this.searchMode = false;
        this.openFolder = this.selectItem = elementLibraryManager.getItemById(folderId);
        this.updatePreview(this.openFolder?.children)
      },
      /**
       * 打开文件夹的Handler
       * @param folderId {string} 文件夹
       * @param from {"cmd"|"library"} 来源，为同步模式添加的
       * @return {Promise<void>}
       */
      async openFolderEventHandler(folderId) {
        // 这里必须关闭检索模式
        this.searchMode = false;
        if (!elementLibraryManager.hasLoad(folderId)) {
          await elementLibraryManager.loadChildrenItem(folderId,cb => {
            this.openFolder = elementLibraryManager.getItemById(folderId);
            // 通用逻辑
            this.updatePreview(this.openFolder.children);
            // knowledgeBaseManager.appendHistoryRecord(HistoryBuilder.buildOpenFolderHistory(folderId));
          });
        } else {
          elementLibraryManager.loadRecord.delete(folderId);
          // 通用逻辑
          this.updatePreview(null);
          // knowledgeBaseManager.appendHistoryRecord(HistoryBuilder.buildOpenFolderHistory(folderId));
        }
      },
      // 更新预览视图列表
      updatePreview(list) {
        this.previewList = list ?? [];
      },
      // 选择项目处理器
      selectItemHandler(item) {
        this.selectItem = item;
      },
      rightClickItem(e, isPreview) {
        this.isPreview = isPreview;
        this.mouseEvent = e;
      },
      // 初始化右键菜单
      initMenu() {
        let menuList = this.isPreview ? elementLibraryItemPreviewMenu : elementLibraryItemMenu;
        return menuList.filter(item => {
          return item.validate(this.selectItem);
        });
      },
      // 初始化事件
      initEvent() {
        //打开文件夹事件监听
        eventBus.on("openElementLibraryFolder", this.openFolderEventHandler);
        // // 前进回退使用的打开文件夹事件
        // eventBus.on("elementLibraryOpenFolder", this.openFolderEventHandlerNoHistory);
        // // 检索记录的回退
        // eventBus.on("searchElementLibraryItem", this.searchItemNoHistory);
        // // 刷新预览窗口
        // eventBus.on("refreshElementLibraryPreview", this.refreshPreview);
        eventBus.on("deleteElementLibraryFolder", this.deleteElementLibraryFolderEventHandler);

        // 同步命令面板和要素库的选中效果
        eventBus.on("ElementLibrarySyncSelectLib", (item) => {
          this.selectItem = item;
        });
      },
      hasGo() {
        let isGo = false;
        if (this.selectItem != null && this.selectItem.children.length > 0) {
          isGo = true;
        }
        return isGo;
      },
      hasBack() {
        let isBack = false;
        if (this.selectItem != null && this.selectItem.folderCode != "0") {
          isBack = true;
        }
        return isBack;
      },
      back() {

      },
      go() {

      },
      addToElementLibrary() {
        let params = {
          cmdName: 'openToolMenu',
          toolName: 'ProgramPlugin-addToElementLibrary',
        }
        elementLibraryCmd.executeElementLibraryCommand(params, res => {

        });
      },
      search() {
        this.openSearch = !this.openSearch;
        if (!this.openSearch) {
          this.searchItem();
        }
      },
      // 检索项目(enter键触发)
      searchEventHandler() {
        this.searchMode = true;
        this.executeSearchItem().then(() => {});
      },
      // 鼠标点击检索按钮
      searchItem() {
        if (this.searchMode || !this.openSearch) {
          this.searchContent = "";
          this.searchResult = [];
          this.openFolderEventHandlerNoHistory(this.openFolder?.id);
        } else {
          // 根据名称检索
          this.searchResult.length = 0;
          if (!this.searchContent.trim().length) return;
          this.executeSearchItem();
          this.searchMode = !this.searchMode;
        }
      },
      executeSearchItem() {
        // 清除上一次检索结果
        this.searchResult = [];
        let folderCode = this.selectItem?.libraryType === LibraryType.FOLDER ? this.selectItem.id : '';
        let params = {
          cmdName: "searchElementLibraryItem",
          searchContent: this.searchContent,
          folderCode: folderCode,
        }
        elementLibraryCmd.executeElementLibraryCommand(params, data => {
          data.forEach(param => {
            let item = new LibraryResultItem(param, elementLibraryManager.findFilePath(param));
            // 添加前确保父文件夹不为undefined
            if (elementLibraryManager.getItemById(item.folderCode) || item.folderCode === '0') {
              elementLibraryManager.addAppendChildren(item.folderCode, item);
              this.searchResult.push(item);
            }
          });
          this.updatePreview(this.searchResult);
        });
      },
      destroyEvent() {
        eventBus.off("openElementLibraryFolder");
        // eventBus.off("knowledgeOpenFolder");
        // eventBus.off("searchKnowledgeItem");
        // eventBus.off("refreshKnowledgePreview");
        eventBus.off("deleteElementLibraryFolder");
        eventBus.off("ElementLibrarySyncSelectLib");
      },
      // 删除文件夹事件回调
      deleteElementLibraryFolderEventHandler(id) {
        let parentFolders = elementLibraryManager.getParentFolders(this.openFolder);
        if (this.openFolder?.id === id || parentFolders.find(folder => folder.id === id)) {
          this.openFolder = null;
        }

        if (this.selectItem?.id === id) {
          this.selectItem = null;
        }
        // 如果正处于搜索
        if (this.searchMode) {
          // 将预览列表中的删除掉
          this.previewList = this.previewList.filter(item => item.id !== id);
        }
      },
    },
    mounted() {
      elementLibraryCmd.init(500, 240, 1000, () => {
        elementLibraryManager.initElementLibrary(cb => {});
      });
    },
  }
</script>

<style scoped>
  .library {
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    flex-direction: column;
    height: 100%;
    font-size: 14px;
  }

  .element-library-toolbar {
    margin-top: 0.25rem;
    margin-bottom: 0.25rem;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    padding: 4px 0.5rem;
  }

  .details-panel {
    letter-spacing: 1px;
    padding: 0.25rem 0.25rem 0.25rem 5px;
  }

  .model-icon {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .text-icon-light {
    color: var(--text-color1);
    background-color: var(--bg-color1);
  }

  .text-icon-light.active, .text-icon-light:hover {
    background-color: var(--bg-color5);
    color: var(--text-color1);
  }

  >>> .base-input-search {
    background-color: var(--bg-color6);
    margin: 0 0.5em;
  }

  >>> .base-input-search > input {
    background-color: var(--bg-color6);
  }

  .preview-position {
    width: 50%;
    text-align: right;
    @apply tw-overflow-hidden tw-text-ellipsis tw-whitespace-nowrap;
  }

  .icon-btn {
    font-size: 22px;
  }

  .medium .icon-btn {
    font-size: 26px;
  }

  .big .icon-btn {
    font-size: 32px;
  }

  .svg-icon {
    width: 1em;
    height: 1em;
    fill: currentColor; /* 图标填充颜色，currentColor是一个变量，表示当前元素的color值，如当前无指定，则从父元素继承 */
    overflow: hidden;
  }
</style>